var newMap = {me:{lat:120.372069,lng:31.508319},user:{},clickMarkers:[]};

$(document).ready(function(){ 
	loadScript();
	$('a.link').bind('click',function(){
		var $this = $(this);
		var top = $this.data('top');
		bindClick('ref',top,500);
	});
	
	//添加标记样式
	$('.market').hover(function(){
		$(this).addClass('market_active');	
	},function(){
		$(this).removeClass('market_active');
	});
	$('.market').click(function(){
		newMap.map.setDefaultCursor("url('./images/mouse.ico')");        
		if($(this).hasClass('market_clicked')) {
			$(this).removeClass('market_clicked');
			newMap.map.removeEventListener("click", showInfo);
			newMap.map.setDefaultCursor("");	
			return;
		}else{
			$(this).addClass('market_clicked');	
			$('.navigation').removeClass('activeNav');	
			clearMarkers();
			//newMap.map.setDefaultCursor("url('mouse.png')");        //设置地图默认的鼠标指针样式
			newMap.map.addEventListener("click", showInfo);
		
		}
		
	});
	
	//显示导航
	var address = $('#address').val('');
	$('#address').click(function(){
		$(this).val('');
	});
	$('#suggestId').focus(function(){
		$('.navigation').removeClass('activeNav');	
		$('.market').removeClass('market_clicked');
		newMap.map.removeEventListener("click", showInfo);	
	});
	$('#suggestId').keyup(function(event){
		if(event.keyCode == 13){        
			$('#confirm').trigger('click');
		}
	});
	$('#confirm').click(function(){
		var address = $('#suggestId').val();
		newMap.map.clearOverlays();    //清除地图上所有覆盖物
		function myFun(){
			var num = local.getResults().getCurrentNumPois();
			if(num < 1) {
				alert('没有找到相关的地点。');
				return;
			}
			newMap.markers = [];
			newMap.infoWindows = [];
			for(var i=0;i<num;i++) {
				var pp = local.getResults().getPoi(i).point;
				newMap.markers[i] = new BMap.Marker(pp);
				if(i==0) {
					newMap.map.centerAndZoom(pp, 18);
				}
				var address = "<h4 style='margin-bottom: 10px;'>"+local.getResults().getPoi(i).title +"</h4><img src='./images/8.png' style='float: left;padding-right: 5px;width: 10px;'/><a href='javascript:void(0);' onClick=showNavigation("+pp.lat+","+pp.lng+")>从这儿出发</a>";
				 addMarker(pp,address);
			}
		}
		var local = new BMap.LocalSearch('无锡', { //智能搜索
		  onSearchComplete: myFun
		});
		local.search(address);	
	});
    $('.navigation').click(function(){
		$(this).addClass('activeNav');
		showNavigation(newMap.user.lat,newMap.user.lng);	
		$('.market').removeClass('market_clicked');
		$(this).removeClass('activeNav');
	});

});

//删除已标记的标记
function clearMarkers(){
	newMap.map.clearOverlays();
	addInitMarker();
}
//添加公司标注
function addInitMarker(){
	var marker1 = new BMap.Marker(new BMap.Point(newMap.me.lat,newMap.me.lng));  // 创建标注
	newMap.map.addOverlay(marker1);   // 将标注添加到地图中
	newMap.map.addControl(new BMap.NavigationControl());  //添加默认缩放平移控件
	//添加信息窗口
	var label = new BMap.Label("无锡福歌科技有限公司",{offset:new BMap.Size(20,-10)});
	marker1.setLabel(label);
}
 
function showNavigation(lat,lng){ 
	var gc = new BMap.Geocoder(); 
	var center = new BMap.Point(newMap.me.lat,newMap.me.lng);
	if(lat == null || lng == null) {
		alert("亲，你还没有选择起点哦~");
		return;
	}
	clearMarkers();
	var startPoint = new BMap.Point(lng,lat);
	//startPoint.setIcon(newMap.icon);
	newMap.marker1 = startPoint;
	var driving = new BMap.DrivingRoute(newMap.map, {renderOptions:{map: newMap.map, autoViewport: true}});
	driving.search(newMap.marker1, center);
	newMap.map.removeEventListener("click", showInfo);	
}

//向地图上添加某地标识
function addMarker(point,info) {
    var marker = new BMap.Marker(point);
	newMap.map.addOverlay(marker);
    var infoWindow = new BMap.InfoWindow(info);
    marker.addEventListener("click", function(){
       this.openInfoWindow(infoWindow);
    });
}

function openMyWin(infoWindow,point){    newMap.map.openInfoWindow(infoWindow,point);    }
//绑定滑动
function bindClick(el,scrollTop,time,callback) {
	$("html,body").animate({scrollTop:scrollTop},time,callback);	
}
function showInfo(e){
   newMap.user.lat = e.point.lat;
   newMap.user.lng = e.point.lng;
  // alert('经度：' + e.point.lng + ", 纬度：" + e.point.lat);
   var point = new BMap.Point(e.point.lng,e.point.lat);
   newMap.map.removeOverlay(newMap.marker1);
   newMap.marker1 = new BMap.Marker(point);  // 创建标注
   newMap.marker1.setIcon(newMap.icon);
   newMap.clickMarkers.push(newMap.marker1);
   newMap.marker1.addEventListener('dragend', function(e){   
    showInfo(e);
   });
   newMap.map.setDefaultCursor("");
   newMap.map.addOverlay(newMap.marker1);
   newMap.map.removeEventListener("click", showInfo);
   $('.market').removeClass('market_clicked');
   var gc = new BMap.Geocoder();
	gc.getLocation(point, function(rs){
		var addComp = rs.addressComponents;
		//alert(addComp.province + ", " + addComp.city + ", " + addComp.district + ", " + addComp.street + ", " + addComp.streetNumber);
		var address = addComp.province+addComp.city+addComp.district+addComp.street+addComp.streetNumber;
		var label = new BMap.Label(address,{offset:new BMap.Size(20,-10)});
		newMap.marker1.setLabel(label);
		newMap.marker1.enableDragging();
	});   
	
}

function loadScript() {  
	var script = document.createElement("script");  
	script.src = "http://api.map.baidu.com/api?v=1.3&callback=initialize";  
	document.body.appendChild(script);
} 
var myValue;
function initialize() {   
	newMap.map = new BMap.Map('map');
	newMap.icon=new BMap.Icon("http://map.baidu.com/image/dest_markers.png",new BMap.Size(32, 32));
	var center = new BMap.Point(newMap.me.lat,newMap.me.lng);
	newMap.map.setCurrentCity('无锡');
	newMap.map.centerAndZoom(center, 16);
	addInitMarker();
	
	var contextMenu = new BMap.ContextMenu();
	var txtMenuItem =
	  {
	   text:'以此为起点',
	   callback:function(p){
		newMap.user.lat = p.lat;
		newMap.user.lng = p.lng;
		newMap.marker1 = new BMap.Marker(p), px = newMap.map.pointToPixel(p);
		clearMarkers();
		newMap.clickMarkers.push(newMap.marker1);
		newMap.marker1.addEventListener('dragend', function(e){   
			showInfo(e);
		});
		
        newMap.marker1.setIcon(newMap.icon); 
		newMap.map.addOverlay(newMap.marker1);
		var gc = new BMap.Geocoder();
		gc.getLocation(p, function(rs){
			var addComp = rs.addressComponents;
			var address = addComp.province+addComp.city+addComp.district+addComp.street+addComp.streetNumber;
			var label = new BMap.Label(address,{offset:new BMap.Size(20,-10)});
			newMap.marker1.setLabel(label);
			newMap.marker1.enableDragging();
		});
	   }
	  }
	 contextMenu.addItem(new BMap.MenuItem(txtMenuItem.text,txtMenuItem.callback,100));
	  contextMenu.addItem(new BMap.MenuItem('显示导航',function(){$('.navigation').trigger('click');},100));
	 contextMenu.addSeparator();
	 contextMenu.addItem(new BMap.MenuItem('放大',function(){newMap.map.zoomIn();},100));
	 contextMenu.addItem(new BMap.MenuItem('缩小',function(){newMap.map.zoomOut();},100));
	 contextMenu.addItem(new BMap.MenuItem('居中',function(evt){newMap.map.setCenter(new BMap.Point(evt.lng,evt.lat));},100)); 
	 newMap.map.addContextMenu(contextMenu);
	var ac = new BMap.Autocomplete(    //建立一个自动完成的对象
		{"input" : "suggestId"
		,"location" : newMap.map
	});
	newMap.ac = ac;
	ac.addEventListener("onhighlight", function(e) {  //鼠标放在下拉列表上的事件		
		var str = "";
		var _value = e.fromitem.value;
		var value = "";
		if (e.fromitem.index > -1) {
			value = _value.province +  _value.city +  _value.district +  _value.street +  _value.business;
		}	
		str = "FromItem<br />index = " + e.fromitem.index + "<br />value = " + value;		
		value = "";
		if (e.toitem.index > -1) {
			_value = e.toitem.value;
			value = _value.province +  _value.city +  _value.district +  _value.street +  _value.business;
		}    
		str += "<br />ToItem<br />index = " + e.toitem.index + "<br />value = " + value;
		G("searchResultPanel").innerHTML = str;
		newMap.ac.setInputValue(_value.business);    
	});
		
	ac.addEventListener("onconfirm", function(e) {    //鼠标点击下拉列表后的事件	
		var _value = e.item.value;
		myValue = _value.province +  _value.city +  _value.district +  _value.street +  _value.business;
		G("searchResultPanel").innerHTML ="onconfirm<br />index = " + e.item.index + "<br />myValue = " + myValue; 
		setPlace();
		newMap.ac.setInputValue(_value.business);    
	});
}
function G(id) {
    return document.getElementById(id);
}

function setPlace(){
	newMap.map.clearOverlays();    //清除地图上所有覆盖物
	function myFun(){
		var pp = local.getResults().getPoi(0).point;    //获取第一个智能搜索的结果
		var keyword = local.getResults().keyword;
		newMap.map.centerAndZoom(pp, 18);
		var mark = new BMap.Marker(pp);
		//mark.setIcon(newMap.icon);
		newMap.map.addOverlay(mark);    //添加标注
		newMap.user.lat = pp.lat;
		newMap.user.lng = pp.lng;
		newMap.marker1 = new BMap.Marker(pp); 
		var label = new BMap.Label(keyword,{offset:new BMap.Size(20,-10)});
		newMap.marker1.setLabel(label);
		//newMap.marker1.setIcon(newMap.icon);
	}
	var local = new BMap.LocalSearch(newMap.map, { //智能搜索
	  onSearchComplete: myFun
	});
	local.search(myValue);
}



	